package com.realworld.controller;

import cn.hutool.core.bean.BeanUtil;
import com.realworld.common.R;
import com.realworld.model.dto.UserInfoReq;
import com.realworld.model.dto.UserInfoResp;
import com.realworld.model.pojo.UserInfo;
import com.realworld.service.UserInfoService;
import com.realworld.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@Api(tags = "人员信息")
@RequestMapping("user")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @GetMapping("hello")
    @ApiOperation("测试")
    public String hello(){
        try {
            int i = 1/0;
        }catch (Exception e){
            R.error(2001,"测试错误！！！");
        }

        return "Hello World";
    }

    @PostMapping("login")
    public R login(@RequestBody UserInfoReq userInfoReq){
        UserInfo user = userInfoService.login(userInfoReq);
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtil.copyProperties(user,userInfoResp);
        //todo 可以优化 存subject的对象没有处理好，导致一会需要id一会需要username  疏忽了
        String token = JwtUtil.createJwt(user.getUsername().toString());
        userInfoResp.setToken(token);
        return R.ok(userInfoResp);
    }

    @PostMapping("register")
    public R register(@RequestBody UserInfoReq userInfoReq){
        return userInfoService.register(userInfoReq);
    }

    @GetMapping
    public R getUserInfo(HttpServletRequest httpServletRequest) throws Exception {
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        UserInfo userInfo = userInfoService.getUserInfo(claims.getSubject());
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtil.copyProperties(userInfo,userInfoResp);
        return R.ok(userInfoResp);
    }

    @PutMapping
    public R updateUserInfo(@RequestBody UserInfoReq userInfoReq,HttpServletRequest httpServletRequest) throws Exception {
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        userInfoReq.setUsername(claims.getSubject());
        return userInfoService.updateUserInfo(userInfoReq);
    }


}
